import XLSX from "xlsx";
var fs = require("fs");
var ch = {
    readFileToJson: function (path, err) {
        var workbook;

        //读取excel
        var data;
        try {
            data = fs.readFileSync(path, "binary"); //, function(err, data) {
        } catch (e) {
            err.msg = e.message;
            return false;
        }

        try {
            workbook = XLSX.read(data, { type: "binary" }); // 以二进制流方式读取得到整份excel表格对象
        } catch (e) {
            err.msg = "合并表读取失败" + e;
            return false;
        }

        // 遍历每张表读取
        for (var sheet in workbook.Sheets) {
            if (workbook.Sheets.hasOwnProperty(sheet)) {

                //转为json对象进行验证操作
                return XLSX.utils.sheet_to_json(workbook.Sheets[sheet], { header: 1 });
            }
        }
        err.msg = "没有sheet"
        return false;
    },
    replace: function (srcData, replaceFile, err) {
        var json = this.readFileToJson(replaceFile, err);
        if (!json)
            return false;

        var key_row = json[0];
        for (var i = 1; i < json.length; i++) {
            var row_data = json[i];
            var id = row_data[0];
            for (var j = 1; j < row_data.length; j++) {
                var value = row_data[j];
                var key = key_row[j];
                if (value && key) {
                    // alert(key);
                    if (!this._replaceItem(srcData, key, id, value, err))
                        return false;
                }
            }
        }

        return true;
    },

    _replaceItem: function (srcData, key, id, value, err) {
        var key_row = srcData[0];
        var replace_colume;
        for (var i = 1; i < key_row.length; i++) {
            if (key_row[i] == key) {
                replace_colume = i;
                break;
            }
        }

        if (!replace_colume) {
            err.msg = "从源中查找替换失败:" + 'key=' + key + ",id=" + id;
            return false;
        };

        for (var i = 1; i < srcData.length; i++) {
            var row_data = srcData[i];
            if (row_data[0] == id) {
                row_data[replace_colume] = value;
                break;
            }
        }

        return true;
    }
}
export default ch;